package com.ddyx.common.framework.filter;

import org.apache.log4j.lf5.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 包装httpRequest,解析JSON
 *
 */
public class JsonRequestWrapper extends HttpServletRequestWrapper {
	// 报文
	private byte[] body = null;
	private String jsonString = null;

	public JsonRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		String method = request.getMethod();
		if ("get".equalsIgnoreCase(method)) {
			return;
		}
		String contentType = request.getContentType();
		if (contentType != null) {
			if (contentType.indexOf("application/json") > -1
					|| contentType.indexOf("text/xml") > -1) {
				body = StreamUtils.getBytes(request.getInputStream());
				if (body != null) {
					jsonString = new String(body, "UTF-8");
				}
			}
		}
	}

	public String getJsonString() {
		return jsonString;
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		/*springboot admin actuator  body为空 启动异常 */
		if (body == null) {
			body = StreamUtils.getBytes(this.getRequest().getInputStream());
		}
		final ByteArrayInputStream bais = new ByteArrayInputStream(body);
		return new ServletInputStream() {
			@Override
			public int readLine(byte[] b, int off, int len) throws IOException {
				return super.readLine(b, off, len);
			}

			@Override
			public boolean isFinished() {
				return false;
			}

			@Override
			public boolean isReady() {
				return false;
			}

			@Override
			public void setReadListener(ReadListener readListener) {

			}

			@Override
			public int read() throws IOException {
				return bais.read();
			}

		};
	}
}